package com.demo216_组合总合3;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        List<List<Integer>> lists = combinationSum3(3, 7);
        System.out.println(lists);
    }

    public static List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> arrayList = new ArrayList<>();
        ArrayList<Integer> path = new ArrayList<>();
        int sum=0;
        dfs(k,n,1,sum,arrayList,path);
        return arrayList;
    }

    private static void dfs(int k, int n, int startIndex, int sum, List<List<Integer>> arrayList, ArrayList<Integer> path) {
        //1.边界条件
        if ((n==sum)&&path.size()==k){
            ArrayList<Integer> copy = new ArrayList<>();
            for (Integer integer : path) {
                copy.add(integer);
            }
            arrayList.add(copy);
            return;
        }
        //2.横向遍历1-9
        for (int i = startIndex; (i <=9)&&(sum+i<=n)&&(path.size()<=k-1); i++) {
            path.add(i);
            sum+=i;
            dfs(k,n,i+1,sum,arrayList,path);
            //3.回溯
            path.remove(path.size()-1);
            sum-=i;
        }
    }
}
